package eyer.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;

public class IPUtils {
    private static Collection<InetAddress> getAllHostAddress() throws SocketException {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        Collection<InetAddress> addresses = new ArrayList<InetAddress>();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement();
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = (InetAddress) inetAddresses.nextElement();
                addresses.add(inetAddress);
            }
        }
        return addresses;
    }

    public static Collection<String> getAllIpv4NoLoopbackAddresses() throws SocketException {
        Collection<String> noLoopbackAddresses = new ArrayList<String>();
        Collection<InetAddress> allInetAddresses = getAllHostAddress();
        for (InetAddress address : allInetAddresses) {
            if (!address.isLoopbackAddress() && address instanceof Inet4Address) {
                noLoopbackAddresses.add(address.getHostAddress());
            }
        }
        return noLoopbackAddresses;
    }

    public static String getFirstNoLoopbackAddress() throws SocketException {
        Collection<String> allNoLoopbackAddresses = getAllIpv4NoLoopbackAddresses();
        return (String) allNoLoopbackAddresses.iterator().next();
    }

    public static String getLocalHostName() {
        try {
            InetAddress netAddress = InetAddress.getLocalHost();
            return netAddress.getHostName();
        } catch (UnknownHostException e) {
        }
        return "";
    }

    public static String getLocalIp() {
        try {
            InetAddress netAddress = InetAddress.getLocalHost();
            return netAddress.getHostAddress();
        } catch (UnknownHostException e) {
        }
        return "";
    }

    public static void main(String[] args) throws SocketException {
        System.out.println(getAllIpv4NoLoopbackAddresses());
        System.out.println(getLocalHostName());
    }
}
